package com.service;

import com.bean.Activity;
import com.bean.User;
import com.mapper.ActivityMapper;
import com.mapper.UserActivityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletRequest;
import java.sql.Date;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

import static com.tool.Tool.getUserId;

/**
 * Created by Yuicon on 2017/3/20.
 */
@Service
public class ActivityService {

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private UserActivityMapper userActivityMapper;

    public List<Activity> findAll(){
        return activityMapper.findAll();
    }

    public List<Activity> findByUserId(ServletRequest req){
        return activityMapper.findByUserId(getUserId(req));
    }

    public Activity findOne(String id){
        Activity activity = activityMapper.findById(id);
        activity.setReadNumber(activity.getReadNumber() + 1);
        activityMapper.update(activity);
        return activity;
    }

    public int insert(Activity activity, ServletRequest req){
        activity.setId(UUID.randomUUID().toString());
        activity.setUserId(getUserId(req));
        activity.setLaunchTime(Date.valueOf(LocalDate.now()));
        return activityMapper.insert(activity);
    }

    public int deleteById(String id, ServletRequest req){
        Optional<Activity> activity = Optional.ofNullable(findOne(id));
        if (activity.isPresent()) {
            if (activity.orElseGet(Activity::new).getId().equals(id)) {
                return activityMapper.deleteById(id);
            }
        }
        return 0;
    }

    public int update(Activity activity, ServletRequest req){
        return activityMapper.update(activity);
    }

    public int campaign(String activityId, ServletRequest req){
        Activity activity = activityMapper.findById(activityId);
        activity.setWillNumber(activity.getWillNumber() + 1);
        activityMapper.update(activity);
        return userActivityMapper.insert(UUID.randomUUID().toString(), getUserId(req), activityId);
    }

    public List<Activity> getActivityByUserId(ServletRequest req){
        return userActivityMapper.findByUserId(getUserId(req));
    }

    public List<User> getUsersByActivityId(String activityId){
        return userActivityMapper.findByActivityId(activityId);
    }
}
